'use client'

import { useState, useEffect } from 'react'
import { useParams, useSearchParams, useRouter } from 'next/navigation'
import { VmsCourse, VmsCourseSection } from '@/types/Model'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'

import { 
  ChevronLeft, 
  ChevronRight, 
  BookOpen, 
  Circle,
  Clock,
  User,
  Menu,
  X
} from 'lucide-react'

export default function CourseLearnPage() {
  const params = useParams()
  const searchParams = useSearchParams()
  const router = useRouter()
  const token = params.token as string
  const currentSectionId = searchParams.get('section')
  
  const [course, setCourse] = useState<VmsCourse | null>(null)
  const [sections, setSections] = useState<VmsCourseSection[]>([])
  const [currentSection, setCurrentSection] = useState<VmsCourseSection | null>(null)
  const [loading, setLoading] = useState(true)
  const [sidebarOpen, setSidebarOpen] = useState(true)

  useEffect(() => {
    fetchCourse()
  }, [token])

  useEffect(() => {
    if (sections.length > 0) {
      const targetSection = currentSectionId 
        ? sections.find(s => s.id === currentSectionId)
        : sections[0]
      setCurrentSection(targetSection || sections[0])
    }
  }, [sections, currentSectionId])

  const fetchCourse = async () => {
    try {
      const response = await fetch(`/api/course/public/${token}`)
      if (!response.ok) throw new Error('Failed to fetch course')
      
      const data = await response.json()
      setCourse(data.course)
      setSections(data.sections?.filter((s: VmsCourseSection) => s.published) || [])
    } catch (error) {
      console.error('Error fetching course:', error)
    } finally {
      setLoading(false)
    }
  }

  const updateURL = (sectionId: string) => {
    const url = new URL(window.location.href)
    url.searchParams.set('section', sectionId)
    router.replace(url.pathname + url.search)
  }

  const setCurrentSectionWithURL = (section: VmsCourseSection) => {
    setCurrentSection(section)
    updateURL(section.id)
  }

  const goToNextSection = () => {
    if (!currentSection) return
    const currentIndex = sections.findIndex(s => s.id === currentSection.id)
    if (currentIndex < sections.length - 1) {
      const nextSection = sections[currentIndex + 1]
      setCurrentSectionWithURL(nextSection)
    }
  }

  const goToPrevSection = () => {
    if (!currentSection) return
    const currentIndex = sections.findIndex(s => s.id === currentSection.id)
    if (currentIndex > 0) {
      setCurrentSectionWithURL(sections[currentIndex - 1])
    }
  }

  const renderContent = (content: string) => {
    return (
      <div className="prose prose-lg prose-slate max-w-none prose-headings:text-slate-800 prose-p:text-slate-600 prose-strong:text-slate-800">
        <ReactMarkdown
          remarkPlugins={[remarkGfm]}
          components={{
            code: ({node, className, children, ...props}) => {
              return (
                <div className="relative my-6">
                  <pre className="bg-slate-900 text-slate-100 rounded-xl p-6 overflow-x-auto shadow-lg border border-slate-200">
                    <code {...props}>{children}</code>
                  </pre>
                </div>
              )
            },
            h1: ({children}) => (
              <h1 className="text-3xl font-bold text-slate-800 mb-6 pb-3 ">{children}</h1>
            ),
            h2: ({children}) => (
              <h2 className="text-2xl font-semibold text-slate-800 mb-4 mt-8">{children}</h2>
            ),
            h3: ({children}) => (
              <h3 className="text-xl font-medium text-slate-800 mb-3 mt-6">{children}</h3>
            ),
            blockquote: ({children}) => (
              <blockquote className="border-l-4 border-blue-500 bg-blue-50 p-4 my-6 rounded-r-lg">
                {children}
              </blockquote>
            )
          }}
        >
          {content}
        </ReactMarkdown>
      </div>
    )
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-4 border-blue-500 border-t-transparent mx-auto mb-4"></div>
          <p className="text-slate-600 font-medium">加载课程中...</p>
        </div>
      </div>
    )
  }

  if (!course || sections.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center">
        <div className="text-center">
          <div className="w-24 h-24 bg-slate-200 rounded-full flex items-center justify-center mx-auto mb-6">
            <BookOpen className="w-12 h-12 text-slate-400" />
          </div>
          <h1 className="text-2xl font-bold text-slate-800 mb-3">课程暂无内容</h1>
          <p className="text-slate-600">请稍后再来查看</p>
        </div>
      </div>
    )
  }

  const currentIndex = currentSection ? sections.findIndex(s => s.id === currentSection.id) : -1

  return (
    <div className="flex h-screen bg-slate-50">
      {/* 移动端遮罩 */}
      {sidebarOpen && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* 左侧章节导航 */}
      <div className={`${
        sidebarOpen ? 'translate-x-0' : '-translate-x-full'
      } fixed lg:relative lg:translate-x-0 z-50 w-80 bg-white shadow-xl border-r border-slate-200 transition-transform duration-300 ease-in-out`}>
        {/* 侧边栏头部 */}
        <div className="p-6 border-b border-slate-200 bg-gradient-to-r from-blue-600 to-blue-700">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold text-white truncate">{course.title}</h2>
            <Button
              variant="ghost"
              size="sm"
              className="lg:hidden text-white hover:bg-white/20"
              onClick={() => setSidebarOpen(false)}
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
          <div className="flex items-center gap-4 text-blue-100 text-sm">
            <div className="flex items-center gap-1">
              <BookOpen className="w-4 h-4" />
              <span>{sections.length} 章节</span>
            </div>
            {course.user && (
              <div className="flex items-center gap-1">
                <User className="w-4 h-4" />
                <span className="truncate">{course.user.name}</span>
              </div>
            )}
          </div>
        </div>
        
        {/* 章节列表 */}
        <div className="overflow-y-auto h-[calc(100vh-140px)]">
          {sections.map((section, index) => {
            const isCurrent = currentSection?.id === section.id
            
            return (
              <div
                key={section.id}
                className={`group relative p-4 border-b border-slate-100 cursor-pointer transition-all duration-200 ${
                  isCurrent 
                    ? 'bg-blue-50 border-l-4 border-l-blue-500 shadow-sm' 
                    : 'hover:bg-slate-50 hover:shadow-sm'
                }`}
                onClick={() => {
                  setCurrentSectionWithURL(section)
                  setSidebarOpen(false)
                }}
              >
                <div className="flex items-start gap-3">
                  <div className="flex-shrink-0 mt-1">
                    <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium ${
                      isCurrent 
                        ? 'bg-blue-500 text-white' 
                        : 'bg-slate-200 text-slate-600 group-hover:bg-slate-300'
                    }`}>
                      {index + 1}
                    </div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-xs text-slate-500 font-medium">第 {index + 1} 章</span>
                      {isCurrent && (
                        <Badge variant="default" className="text-xs bg-blue-500 hover:bg-blue-600">
                          当前
                        </Badge>
                      )}
                      {section.is_free && (
                        <Badge variant="outline" className="text-xs border-green-500 text-green-600">
                          免费
                        </Badge>
                      )}
                    </div>
                    <h3 className={`text-sm font-medium leading-tight ${
                      isCurrent ? 'text-blue-700' : 'text-slate-800 group-hover:text-slate-900'
                    }`}>
                      {section.title}
                    </h3>
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* 顶部工具栏 */}
        <div className="bg-white border-b border-slate-200 px-6 py-4 shadow-sm">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Button
                variant="ghost"
                size="sm"
                className="lg:hidden"
                onClick={() => setSidebarOpen(true)}
              >
                <Menu className="w-4 h-4" />
              </Button>
              
              <div className="flex items-center gap-3">
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={goToPrevSection}
                  disabled={currentIndex <= 0}
                  className="shadow-sm hover:shadow-md transition-shadow"
                >
                  <ChevronLeft className="w-4 h-4 mr-1" />
                  上一章
                </Button>
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={goToNextSection}
                  disabled={currentIndex >= sections.length - 1}
                  className="shadow-sm hover:shadow-md transition-shadow"
                >
                  下一章
                  <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              </div>
            </div>
            
            {/* 进度指示器 */}
            {currentSection && (
              <div className="hidden md:flex items-center gap-3 text-sm text-slate-600">
                <span className="font-medium">
                  {currentIndex + 1} / {sections.length}
                </span>
                <div className="w-32 h-2 bg-slate-200 rounded-full overflow-hidden">
                  <div 
                    className="h-full bg-blue-500 transition-all duration-300 ease-out"
                    style={{ width: `${((currentIndex + 1) / sections.length) * 100}%` }}
                  />
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 章节内容 */}
        <div className="flex-1 overflow-y-auto bg-white">
          {currentSection ? (
            <div className="max-w-4xl mx-auto px-6 py-8">
              {/* 章节标题 */}
              <div className="mb-8 pb-6 border-b border-slate-200">
                <div className="flex items-center gap-3 mb-3">
                  <Badge variant="outline" className="text-blue-600 border-blue-200">
                    第 {currentIndex + 1} 章
                  </Badge>
                  {currentSection.is_free && (
                    <Badge variant="outline" className="text-green-600 border-green-200">
                      免费章节
                    </Badge>
                  )}
                </div>
                {/* <h1 className="text-3xl font-bold text-slate-800 mb-3">
                  {currentSection.title}
                </h1> */}
                <div className="flex items-center gap-4 text-sm text-slate-500">
                  <div className="flex items-center gap-1">
                    <Clock className="w-4 h-4" />
                    <span>预计阅读时间 5-10 分钟</span>
                  </div>
                </div>
              </div>

              {/* 章节内容 */}
              <Card className="border-0 shadow-sm">
                <CardContent className="p-0">
                  {currentSection.content_md ? (
                    renderContent(currentSection.content_md)
                  ) : (
                    <div className="text-center py-16">
                      <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <BookOpen className="w-8 h-8 text-slate-400" />
                      </div>
                      <p className="text-slate-500 text-lg">该章节暂无内容</p>
                      <p className="text-slate-400 text-sm mt-2">内容正在准备中，请稍后查看</p>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 章节导航 */}
              <div className="flex items-center justify-between mt-8 pt-6 border-t border-slate-200">
                <div>
                  {currentIndex > 0 && (
                    <Button 
                      variant="outline" 
                      onClick={goToPrevSection}
                      className="shadow-sm hover:shadow-md transition-all"
                    >
                      <ChevronLeft className="w-4 h-4 mr-2" />
                      <div className="text-left">
                        <div className="text-xs text-slate-500">上一章</div>
                        <div className="font-medium">{sections[currentIndex - 1]?.title}</div>
                      </div>
                    </Button>
                  )}
                </div>
                <div>
                  {currentIndex < sections.length - 1 && (
                    <Button 
                      onClick={goToNextSection}
                      className="shadow-sm hover:shadow-md transition-all"
                    >
                      <div className="text-right">
                        <div className="text-xs text-blue-100">下一章</div>
                        <div className="font-medium">{sections[currentIndex + 1]?.title}</div>
                      </div>
                      <ChevronRight className="w-4 h-4 ml-2" />
                    </Button>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <BookOpen className="w-8 h-8 text-slate-400" />
                </div>
                <p className="text-slate-500 text-lg">请选择一个章节开始学习</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}